# 规则名称
$ruleName = [char]0x0052 + [char]0x0050 + [char]0x0047 + [char]0x670D + [char]0x6D88 + [char]0x5931 + [char]0x5427

# 防火墙规则地址
$remoteIpAddressesUrl = "https://gitee.com/yuukitriple/left4-dead2-without-rpg/raw/master/rule.txt"

# 检查注册表获取 Steam 安装路径
$steamRegistryPath = "HKLM:\SOFTWARE\Wow6432Node\Valve\Steam"
$steamInstallPath = (Get-ItemProperty -Path $steamRegistryPath).InstallPath

if ($steamInstallPath -eq $null) {
    Write-Host "未找到 Steam 安装路径。请检查 Steam 是否已安装。"
    exit 1
}

# 构建 Left 4 Dead 2 完整路径
$left4Dead2Path = Join-Path $steamInstallPath "steamapps\common\Left 4 Dead 2\left4dead2.exe"

# 打印路径到控制台
Write-Host "Left 4 Dead 2 路径: $left4Dead2Path"

# 尝试删除旧的入站规则
try {
    $existingInboundRule = Get-NetFirewallRule -DisplayName ($ruleName + "_in")
    if ($existingInboundRule -ne $null) {
        Remove-NetFirewallRule -DisplayName ($ruleName + "_in")
        Write-Host "已删除旧的入站规则: $($ruleName + "_in")"
    } else {
        Write-Host "未找到旧的入站规则: $($ruleName + "_in")"
    }
} catch {
    Write-Host "无法删除旧的入站规则。错误信息: $_"
}

# 尝试删除旧的出站规则
try {
    $existingOutboundRule = Get-NetFirewallRule -DisplayName ($ruleName + "_Out")
    if ($existingOutboundRule -ne $null) {
        Remove-NetFirewallRule -DisplayName ($ruleName + "_Out")
        Write-Host "已删除旧的出站规则: $($ruleName + "_Out")"
    } else {
        Write-Host "未找到旧的出站规则: $($ruleName + "_Out")"
    }
} catch {
    Write-Host "无法删除旧的出站规则。错误信息: $_"
}

# 从网络文件中获取远程 IP 地址列表
try {
    $remoteIpAddressesList = (Invoke-WebRequest -Uri $remoteIpAddressesUrl -UseBasicParsing).Content -split "`r`n"
} catch {
    Write-Host "无法获取远程 IP 地址列表。错误信息: $_"
    exit 1 
}

# 将文本样式打印到控制台
Write-Host "防火墙规则:"
Write-Host ($remoteIpAddressesList -join "`n")

# 创建入站规则
New-NetFirewallRule -DisplayName ($ruleName + "_in") -Direction Inbound -Action Block -Program $left4Dead2Path -RemoteAddress $remoteIpAddressesList -Profile Domain, Private, Public

# 创建出站规则
New-NetFirewallRule -DisplayName ($ruleName + "_Out") -Direction Outbound -Action Block -Program $left4Dead2Path -RemoteAddress $remoteIpAddressesList -Profile Domain, Private, Public

Start-Sleep -Seconds 3